package cn.ac.iscas.domain.component;


import cn.ac.iscas.domain.common.ExceptionHandleMode;
import cn.ac.iscas.domain.view.ParameterItem;

import com.iscas.datasong.lib.common.DataSongException;
import com.iscas.datasong.lib.common.Status;
import com.iscas.datasong.lib.util.DataSongStringUtils;


import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by ISCAS on 2017/9/27.
 *
 * 转换器通用参数
 */

public class ComponentParameter implements IComponentParameter {
	protected ExceptionHandleMode mode;

	/**
	 * 组件参数
	 */
	protected List<ParameterItem> viewParams;

	@Override
	public Map<String, Object> getSimpleParameter() throws DataSongException {
		Map<String, Object> parameter = new HashMap<>();
		if(viewParams != null){
			for(ParameterItem tmp : viewParams){
				parameter.put(tmp.getId(), tmp.getValue());
			}
		}

		return parameter;
	}

	@Override
	public boolean validate() throws DataSongException {
		if(viewParams!=null){
			for(ParameterItem tmp : viewParams){
				validateItem(tmp);
			}
		}

		return true;
	}

	private boolean validateItem(ParameterItem item) throws DataSongException {
		//检查必填项是否满足
		if(item.isRequired() &&
				(item.getValue() == null ||  DataSongStringUtils.isEmpty(item.getValue().toString()))){
			throw new DataSongException(Status.PARAM_ERROR, String.format("the value of parameter [%s] is required", item.getLabel()));
		}

		//正则检查
		if(DataSongStringUtils.isNotEmpty(item.getRegex()) && item.getValue() != null ){
			String regex = item.getRegex();
			if(regex.startsWith("/^")){ //适配js的正则表达式
				regex = regex.substring(2);
			}else if(regex.startsWith("/")){
				regex = regex.substring(1);
			}

			if(regex.endsWith("$/")){ //适配js的正则表达式
				regex = regex.substring(0,regex.length()-2);
			}else if(regex.endsWith("/")){
				regex = regex.substring(0,regex.length()-1);
			}

			Pattern pattern = Pattern.compile(regex);
			Matcher matcher = pattern.matcher(item.getValue().toString());
			if(!matcher.matches()){
				throw new DataSongException(Status.PARAM_ERROR,
						String.format("the value of parameter [%s] is illegal",item.getLabel()));
			}
		}

		return true;
	}

	public ExceptionHandleMode getMode() {
		return mode;
	}

	public void setMode(ExceptionHandleMode mode) {
		this.mode = mode;
	}

	public List<ParameterItem> getViewParams() {
		return viewParams;
	}

	public void setViewParams(List<ParameterItem> viewParams) {
		this.viewParams = viewParams;
	}
}
